<template>
  <div>
    <el-upload
      v-bind="$attrs"
      list-type="picture-card"
      :accept="accept"
      :action="action"
      :headers="{token: qiNiuToken}"
      :data="{token: qiNiuToken}"
      :limit="limit"
      :auto-upload="true"
      :show-file-list="true"
      :file-list="fileList"
      :multiple="true"
      :on-change="onChange"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-success="onSuccess"
      :on-error="onError"
      :on-progress="onProgress"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :on-exceed="onExceed"
      v-on="$listeners"
    >
      <template #trigger>
        <div :style="{width, height}">
          <div style="width: 100%; height: 100%;">
            <el-icon name="plus" />
          </div>
        </div>
      </template>
      <div slot="file" slot-scope="{file}">
        <div style="width: 100%;height: 100%;position: relative;">
          <div
            style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;background-color: #00000050;
                display: flex; justify-content: center;align-items: center; column-gap: 24px;z-index: 1"
            :style="{height}"
          >
            <template v-if="file.percent">
              <el-progress class="progress" :percentage="parseInt(file.percent.toFixed(0))" type="circle" :text-color="'#ffffff'" :show-text="true" />
            </template>
            <template v-else>
              <div @click="onPreview(file)">
                <el-icon name="search" style="font-size: 24px; color: white; cursor: pointer" />
              </div>

              <div @click="onRemove(file)">
                <el-icon name="delete" style="font-size: 24px; color: white; cursor: pointer" />
              </div>
            </template>
          </div>
          <img v-if="type === 'img'" :src="file.url" style="width: 100%; height: 100%">
          <video v-if="type === 'video'" :src="file.url" style="width: 100%; height: 100%" />
        </div>

      </div>
    </el-upload>
    <el-dialog :visible="dialogVisible" :append-to-body="true" :close-on-click-modal="false" @close="dialogVisible = false">
      <div style="width: 100%; display: flex; justify-content: center">
        <el-image v-if="type === 'img'" :src="previewUrl" fit="contain" />
        <video v-if="type === 'video'" :src="previewUrl" style="width: 100%" :controls="true" />
      </div>
    </el-dialog>
  </div>

</template>
<script>
import { uploadToken } from '@/api/base'
export default {
  name: 'Upload',
  props: {
    // 宽度
    width: {
      type: String,
      default: '146px'
    },
    // 高度
    height: {
      type: String,
      default: '146px'
    },
    // 已上传文件列表
    fileList: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 最大文件数量限制
    limit: {
      type: Number,
      default: 1
    },
    // 文件类型
    type: {
      type: String,
      default: 'img'
    }
  },
  data() {
    return {
      action: '',
      previewUrl: '',
      dialogVisible: false,
      qiNiuToken: '',
      qiNiuHost: ''
    }
  },
  computed: {
    // 根据文件类型控制可选的文件
    accept() {
      let accept = null
      if (this.type === 'img') {
        accept = '.jpg,.png'
      } else if (this.type === 'video') {
        accept = '.mp4'
      }
      return accept
    }
  },
  methods: {
    // 文件列表更新
    _onUpdate(fileList) {
      this.$emit('on-update', fileList)
    },
    // 文件列表项增加
    onChange(file, fileList) {
      console.log('文件改变')
      this._onUpdate(fileList)
    },
    // 点击删除按钮
    onRemove(file) {
      console.log('文件删除')
      const fileList = this.fileList.filter((item) => {
        return item.url !== file.url
      })
      this._onUpdate(fileList)
    },
    // 点击预览按钮
    onPreview(file) {
      console.log('点击预览按钮')
      this.previewUrl = file.url
      this.dialogVisible = true
    },
    // 上传前
    async beforeUpload(file) {
      console.log('文件上传前钩子')
      try {
        const qiNiuInfoRes = await uploadToken()
        console.log('七牛信息', qiNiuInfoRes)
        this.action = qiNiuInfoRes.data.bucket_url
        this.qiNiuToken = qiNiuInfoRes.data.token
        this.qiNiuHost = qiNiuInfoRes.data.host
      } catch (error) {
        this.$errorMessage()
        return false
      }
    },
    // 成功
    async onSuccess(res, file) {
      console.log('文件上传成功')
      this.$set(file, 'percent', 0)
      file.url = (this.qiNiuHost + res.key).replace('https', 'http')
    },
    // 失败
    onError() {
      this.$errorMessage('文件上传失败')
    },
    // 超出数量限制
    onExceed() {
      this.$errorMessage('文件超出数量限制')
    },
    // 上传进度
    onProgress(event, file, fileList) {
      console.log('文件上传进度更新', event.percent)
      this.$set(file, 'percent', event.percent)
    },
    // 移除前
    beforeRemove() {
      console.log('文件移除前钩子')
    }
  }
}
</script>
<style lang="scss" scoped>
.progress::v-deep .el-progress__text {
  color: white
}
</style>
